/* eslint-disable no-param-reassign */
/* eslint-disable import/prefer-default-export */
/* eslint-disable no-unused-vars */

import CryptoJS from 'crypto-js';

const key = [86, 2, 70, 117, 90, 122, 107, 121, 78, 106, 81, 1, 78, 71, 82, 84];
const iv = 9;

const parseK = (k) => k.reduce((result, i) => result + (i < 10 ? i : String.fromCharCode(i)), '');
const parseV = (v) => [...v].reverse().reduce((r, i, j) => `${i}${r}${j + 1}`, '');
const parseV0 = (num) => {
  const a = key[num] - num; let b = '';
  // eslint-disable-next-line no-plusplus
  while (--num) {
    b += String.fromCharCode(a + num - 1);
  }
  return [...b].reverse().join('');
};

// 加密
function encrypt(text) {
  return CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(parseK(key)), {
    iv: CryptoJS.enc.Utf8.parse(parseV(parseV0(iv))),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
}

// 解密
function decrypt(text) {
  const result = CryptoJS.AES.decrypt(text, CryptoJS.enc.Utf8.parse(parseK(key)), {
    iv: CryptoJS.enc.Utf8.parse(parseV(parseV0(iv))),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return result.toString(CryptoJS.enc.Utf8);
}

export function encryptStr(text) {
  return encrypt(text).toString();
}

export default encryptStr;
